<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button
          class="filter-item"
          style="margin-left: 10px"
          type="primary"
          @click="handleCreateCategory"
      >
        <el-icon style="vertical-align: middle">
          <Plus/>
        </el-icon>
        添加分类
      </el-button>
    </div>
    <el-table
        v-loading="state.listLoading"
        :data="state.list"
        :load="state.listLoading"
        row-key="category_id"
        border
        default-expand-all
        style="width: 100%">
      <el-table-column
          label="名称"
          prop="name"
          align="left"
          width="270">
      </el-table-column>
      <el-table-column
          label="key or url"
          prop="categoryKey"
          align="left"
          width="650">
        <template #default="scope">
          <el-tag
              class="el-table-tag"
              size="small"
              v-if="scope.row.url != null"
              v-for="item in scope.row.url.split(',')"
          ><span v-text="item"/></el-tag>
        </template>
      </el-table-column>
      <el-table-column label="" width="220" align="right">
        <template #default="scope">
          <el-button size="small" 
                     v-if="scope.row.is_parent === true"
                     @click="handleCreatePerm(scope.row)"
          >添加下级
          </el-button>
          <el-button size="small"
                     v-if="scope.row.is_parent === true"
                     @click="handleUpdateCategory(scope.row)"
          >编辑
          </el-button>
          <el-button size="small"
                     v-else
                     @click="handleUpdatePerm(scope.row)"
          >编辑
          </el-button>
          <el-popconfirm title="确认删除?"
                         v-if="scope.row.is_parent === true"
                         @confirm="handleDeleteCategory(scope.row)">
            <template #reference>
              <el-button
                  size="small"
                  type="danger"
              >删除
              </el-button>
            </template>
          </el-popconfirm>
          <el-popconfirm title="确认删除?"
                         v-else
                         @confirm="handleDeletePerm(scope.row)">
            <template #reference>
              <el-button
                  size="small"
                  type="danger"
              >删除
              </el-button>
            </template>
          </el-popconfirm>
          <el-popconfirm/>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
        :title="state.textMap[state.dialogCategoryStatus]"
        v-model="state.dialogCategoryFormVisible"
    >
      <el-form
          ref="dataForm"
          :rules="state.categoryRules"
          :model="state.defaultCategoryModel"
          label-position="left"
          label-width="100px"
          style="width: 400px; margin-left: 50px"
      >
        <el-form-item
            label="分类名称"
            prop="name"
        >
          <el-input v-model="state.defaultCategoryModel.name"
                    maxlength="20"
                    show-word-limit/>
        </el-form-item>
        <el-form-item
            label="key"
            prop="categoryKey"
        >
          <el-input v-model="state.defaultCategoryModel.categoryKey"
                    maxlength="20"
                    show-word-limit/>
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button @click="state.dialogCategoryFormVisible = false">
          取消
        </el-button>
        <el-button
            type="primary"
            @click="state.dialogCategoryStatus === 'create' ? createCategory() : updateCategory()"
        >
          确定
        </el-button>
      </div>
    </el-dialog>

    <el-dialog
        :title="state.textPermMap[state.dialogPermStatus]"
        v-model="state.dialogPermFormVisible"
    >
      <el-form
          ref="dataForm"
          :rules="state.permRules"
          :model="state.defaultPermModel"
          label-position="left"
          label-width="117px"
          style="width: 400px; margin-left: 50px"
      >
        <el-form-item
            label="权限名称"
            prop="name"
        >
          <el-input v-model="state.defaultPermModel.name"
                    maxlength="20"
                    show-word-limit/>
        </el-form-item>
        <el-form-item
            label="鉴权匹配url    (多个逗号隔开)"
            prop="url"

        >
          <el-input v-model="state.defaultPermModel.url"             
                    maxlength="200"
                    :autosize="{minRows: 3, maxRows: 5}"
                    type="textarea"
                    show-word-limit/>
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button @click="state.dialogPermFormVisible = false">
          取消
        </el-button>
        <el-button
            type="primary"
            @click="state.dialogPermStatus === 'create' ? createPerm() : updatePerm()"
        >
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  reactive,
  onMounted,
  ref
} from 'vue'
import {get, post, put, del, handleRegexpTxt} from '@/utils/http'
import {ElForm} from 'element-plus'
import {apis} from '@/apis'
import {cloneDeep} from 'lodash'

const dataForm = ref(ElForm)
const categoryModel = {
  id: null,
  name: '',
  categoryKey: ''
}
const permModel = {
  id: null,
  name: '',
  url: '',
  categoryId: null
}
const state = reactive({
  list: [],
  listLoading: true,
  textMap: {
    update: '编辑权限分类',
    create: '添加权限分类'
  },
  textPermMap: {
    update: '编辑权限',
    create: '添加权限'
  },
  dialogCategoryStatus: '',
  dialogCategoryFormVisible: false,
  defaultCategoryModel: categoryModel,
  categoryRules: {
    name: [
      {required: true, message: '请输入分类名称', trigger: 'change'}
    ],
    categoryKey: [
      {required: true, message: '请输入key', trigger: 'change'}
    ]
  },
  dialogPermStatus: '',
  dialogPermFormVisible: false,
  defaultPermModel: permModel,
  permRules: {
    name: [
      {required: true, message: '请输入权限名称', trigger: 'change'}
    ],
    url: [
      {required: true, message: '请输入url', trigger: 'change'}
    ]
  },
})

const handleList = () => {
  state.listLoading = true
  state.list = []
  get(apis.ALL_PERM_CATEGORY).then((res) => {
    for (const item of res.data) {
      const permCategoryModel = {
        id: item.id,
        category_id: item.id,
        name: item.name,
        categoryKey: item.categoryKey,
        is_parent: true,
        children: item.children
      }
      state.list.push(permCategoryModel)
    }
    console.log(state.list)
    state.listLoading = false
  })
}

const resetCategory = () => {
  state.defaultCategoryModel = cloneDeep(categoryModel)
}

const resetPerm = () => {
  state.defaultPermModel = cloneDeep(permModel)
}

const handleCreateCategory = () => {
  resetCategory()
  state.dialogCategoryStatus = 'create'
  state.dialogCategoryFormVisible = true
}

const handleUpdateCategory = (row) => {
  resetCategory()
  state.dialogCategoryStatus = 'update'
  state.dialogCategoryFormVisible = true
  state.defaultCategoryModel = row
}

const handleDeleteCategory = (row) => {
  let onePermCategory = handleRegexpTxt(apis.ONE_PERM_CATEGORY, '{id}', row.id);
  del(onePermCategory).then((res) => {
    handleList()
  })
}

const handleCreatePerm = (row) => {
  resetPerm()
  state.dialogPermStatus = 'create'
  state.dialogPermFormVisible = true
  state.defaultPermModel.categoryId = row.id
}

const handleUpdatePerm = (row) => {
  resetCategory()
  state.dialogPermStatus = 'update'
  state.dialogPermFormVisible = true
  state.defaultPermModel = row
}

const handleDeletePerm = (row) => {
  let onePerm = handleRegexpTxt(apis.ONE_PERM, '{id}', row.id);
  del(onePerm).then((res) => {
    handleList()
  })
}

const createCategory = () => {
  const form = ref(dataForm)
  form.value.validate(async (valid) => {
    if (valid) {
      post(apis.PERM_CATEGORY, state.defaultCategoryModel).then((res) => {
        state.dialogCategoryFormVisible = false
        handleList()
      })
    }
  })
}

const updateCategory = () => {
  const form = ref(dataForm)
  let onePerm = handleRegexpTxt(apis.ONE_PERM_CATEGORY, '{id}', state.defaultCategoryModel.id);
  form.value.validate(async (valid) => {
    if (valid) {
      put(onePerm, state.defaultCategoryModel).then((res) => {
        state.dialogCategoryFormVisible = false
        handleList()
      })
    }
  })
}

const createPerm = () => {
  const form = ref(dataForm)
  form.value.validate(async (valid) => {
    if (valid) {
      post(apis.PERM, state.defaultPermModel).then((res) => {
        state.dialogPermFormVisible = false
        handleList()
      })
    }
  })
}

const updatePerm = () => {
  const form = ref(dataForm)
  let onePerm = handleRegexpTxt(apis.ONE_PERM, '{id}', state.defaultPermModel.id);
  form.value.validate(async (valid) => {
    if (valid) {
      put(onePerm, state.defaultPermModel).then((res) => {
        state.dialogPermFormVisible = false
        handleList()
      })
    }
  })
}

onMounted(() => {
  handleList()
})

</script>

<style>
.el-table-tag{
  margin-right: 5px;
}
</style>
